from django import template
from django.utils.safestring import mark_safe
from sanitize import sanitize
register = template.Library()

class RenderNode(template.Node):

    def __init__(self, content):
        self.content = content
        self.resolved_content = None

    def render(self, context):
        try:
	    self.resolved_content = template.resolve_variable(self.content, context)
            return template.Template(self.resolved_content).render(template.Context(context, autoescape=False))
        except template.TemplateSyntaxError, e:
            return mark_safe("<strong>Template error: There is an error one of this page's template tags: <code>%s</code></small>" % e.message)

class RenderSanitizeNode(RenderNode):
    def render(self, context):
	return sanitize(super(RenderSanitizeNode,self).render(context))

@register.tag(name='render')
def django_render(parser, token):
    " Example: {% render flatpage.content %}"
    content = token.split_contents()[-1]
    return RenderNode(content)
django_render.is_safe = True

@register.tag(name='render_sanitize')
def django_render_sanitize(parser, token):
    " Example: {% render_sanitize flatpage.content %}"
    content = token.split_contents()[-1]
    return RenderSanitizeNode(content)
django_render_sanitize.is_safe = True
